import { System } from "csharp";
import { $typeof } from "puerts";

/**
 * DOS管理
 * @author clong 2021.02.06
 */
export default class DosMgr {

    private static inst: DosMgr = null;
    public static get Inst(): DosMgr {
        return this.inst = this.inst || new DosMgr();
    }

    private p: System.Diagnostics.Process;

    constructor() {

    }

    init(): void {
        //https://www.cnblogs.com/xuliangxing/p/5993297.html

        try {

            // console.log("--------------->启动 DOS.  Process: " + System.Diagnostics.Process );

            // let process:Array<System.Diagnostics.Process> = System.Diagnostics.Process.GetProcesses();
            // console.log( "---->process.length: " + process.length );
            // if( process && process.length > 0 ){
            //     for( let i=0;i<process.length;i++ ){
            //         console.log( "---->fileName: " + process[i].StartInfo.FileName );
            //     }
            // }            

            let Process:any = $typeof(System.Diagnostics.Process);
            console.log("--------------->启动 DOS.  Process: " + Process );

            // this.p = System.Diagnostics.Process.Start();//"cmd.exe"
            this.p = Process.Start();// new System.Diagnostics.Process();
            this.p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            this.p.StartInfo.FileName = "cmd.exe";
            this.p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            this.p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            this.p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            this.p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            this.p.OutputDataReceived = (sendingProcess: any, outLine: any) => { this.OutputDataReceived(sendingProcess, outLine) }
            this.p.Start();//启动程序
            this.p.BeginOutputReadLine();            
        } catch (error) {
            console.log("------------->error: " + error);
        }        
    }

    private OutputDataReceived(sendingProcess: any, outLine: any): void {

        // if (!String.IsNullOrEmpty(outLine.Data)) {
            //   StringBuilder sb = new StringBuilder(this.textBox1.Text);
            //   this.textBox1.Text = sb.AppendLine(outLine.Data).ToString();
            //   this.textBox1.SelectionStart =this.textBox1.Text.Length;
            //   this.textBox1.ScrollToCaret();
        // }
        console.log( "-------------接收数据" );
        if( outLine && outLine.Data ){

            console.log( "-------------输出: " + outLine.Data );
            // console.log( JSON.stringify(outLine.Data) );
        }
    }
}